package com.dao;

import com.entity.user;
import com.util.DBCUtil;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class UserInfDao {
        public <T> List<T> getForList(Class<T> clazz, String sql, Object... args) {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                conn = DBCUtil.getConnection();
                ps = conn.prepareStatement(sql);
                for (int i = 0; i < args.length; i++) {
                    ps.setObject(i + 1, args[i]);
                }
                rs = ps.executeQuery();
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnCount = rsmd.getColumnCount();
                ArrayList<T> list = new ArrayList<T>();
                while (rs.next()) {
                    T t = clazz.getDeclaredConstructor().newInstance();
                    for (int i = 0; i < columnCount; i++) {
                        Object columValue = rs.getObject(i + 1);
                        String columnLabel = rsmd.getColumnLabel(i + 1);
                        Field field = clazz.getDeclaredField(columnLabel);
                        field.setAccessible(true);
                        field.set(t, columValue);
                    }
                    list.add(t);
                }
                return list;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                DBCUtil.close(rs, ps, conn);
            }
            return null;
        }
    public void update(String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBCUtil.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBCUtil.close(rs, ps, conn);
        }
    }
}

